<script setup>
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {userAddNewAddrService} from "@/api/user.js";
import {useOrderInfoStore} from "@/stores/index.js";

// 是否显示弹框
const dialogVisible = defineModel()
// 拿到userId
const useUserInfo = useOrderInfoStore()
// 收集数据
const addressForm = ref({
  name: '',
  userId: 0,
  phone: '',
  address: '',
  status: 0
})
// 表单对象
const form = ref()
// 校验规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^[0-9]{10,11}$/, message: '请输入有效的电话号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}
// 提交函数
const submitAddress = async () => {
  // 表单预校验
  // await addressForm.value.validate((valid, errObj) => {
  //   valid && console.log('表单校验通过')
  // })
  addressForm.value.userId = useUserInfo.orderInfo.userId
  addressForm.value.status = 0
  await userAddNewAddrService(addressForm.value)
  console.log(addressForm.value)
  handleClose()
  dialogVisible.value = false
  ElMessage.success("新增地址成功")
}
// 关闭弹框，清除数据
const handleClose = () => {
  addressForm.value.name = ''
  addressForm.value.phone = ''
  addressForm.value.address = ''
}
</script>

<template>
  <el-dialog
      @close="handleClose"
      v-model="dialogVisible"
      title="新增地址"
      width="500"
  >
    <el-form :model="addressForm"
             :rules="rules"
             ref="form"
             @keyup.enter="submitAddress">
      <el-form-item label="姓名" prop="name">
        <el-input
            name="name"
            placeholder="请输入姓名"
            v-model="addressForm.name">
        </el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
            name="phone"
            placeholder="请输入电话"
            v-model="addressForm.phone">
        </el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
            name="address"
            placeholder="请输入地址"
            v-model="addressForm.address"
            type="textarea">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddress">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
  padding-right: 20px;
}
</style>
